/**
 * Created with IntelliJ IDEA
 * Description:
 * User: SEKI TOMOKI
 * Date: 2023-10-04
 * Time: 13:58
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode newH = new ListNode();//虚拟节点
        ListNode tmpH = newH;//跟踪新链表中的最后一个节点

        while(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                tmpH.next = list1;
                tmpH = tmpH.next;
                list1 = list1.next;
            }else {
                tmpH.next = list2;
                tmpH = tmpH.next;
                list2 = list2.next;
            }
            //tmpH = tmpH.next;可以只写成一条语句
        }

        //走到这一步一定有一个链表走到走到尽头，那把另一个链表的引用连接即可
        if(list1 != null) {
            tmpH.next = list1;
        }
        if(list2 != null) {
            tmpH.next = list2;
        }
        return newH.next;
    }
}
